/*
 * USART_0.c
 *
 * Created: 11/13/2012 12:15:59 AM
 *  Author: Hp-Minion
 */ 
/*****************************************************************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
#include "General.h"
#include "USART_0.h"
#include "Port.h"
/*****************************************************************************************/
void USART_InitUSART()
{
	UCSR0B = (1<<RXCIE0) | (1<<RXEN0) | (1<<TXEN0);
	UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);
	UBRR0L = 103;
	UBRR0H = 0;
	PinMode(13,'D',OUTPUT);
}
/*****************************************************************************************/
unsigned char USART_Receive(void)
{
	unsigned char state;
	/* Wait for data to be received */
	if ((UCSR0A & (1<<RXC0)))
	{
		state = UDR0;		/* Get and return received data from buffer */
	}	
	else
	{
		state = 0;
	}
	
	return state;
}
/*****************************************************************************************/
void USART_Write( char *data, unsigned char length)
{
	unsigned char i = 0;
	while (length > 0)
	{
		// Wait for buffers to be free
		if (UCSR0A & (1<<UDRE0))
		{
			UDR0 = data[i++];
			length--;
		}
	}
	
	// Wait for transmission to be ready
	while (!(UCSR0A & (1<<TXC0)))
		;
}
/*****************************************************************************************/
void USART_Flush(void)
{
    unsigned char dummy;
    while ( UCSR0A & (1<<RXC0) ) dummy = UDR0;
}
/*****************************************************************************************/
void USART_vBlinkLed(void)	
{	
    char outputString[2];
			
 	outputString[1] = USART_Receive();
  	if (outputString[1] == 'a')
  	{
  		DigitalWrite(13,HIGH);
		USART_Flush();
  	}
  	else 
  	{
  		if(outputString[1] == 's')
  		{
  			DigitalWrite(13,LOW);
	    	USART_Flush();
		}	
  	}
}
/*****************************************************************************************/
void serialPrint( char * text)
{
    unsigned char length = strlen(text);
	USART_Write(text, length);
	USART_Flush();
}
/*****************************************************************************************/
void PRINT_u8(char* text, unsigned char value)
{
	char nString[USART_MAX_STR_PRINT_SIZE];
	sprintf(nString, text, value);
	serialPrint(nString);
}
/*****************************************************************************************/
ISR(USART_RX_vect)
{
	
}
/*****************************************************************************************/